package com.zhz.mall.common.util.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

/**
 * @description: spring上下文
 * @motto: 代码源于生活，高于生活艺术
 * @author: zhouhengzhe
 * @date: 2023/1/12 15:40
 * @since 1.0
 **/
@Slf4j
public class SpringApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public SpringApplicationContextHolder() {
        log.info("### ygp-base init : YgpSpringContext ###");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringApplicationContextHolder.applicationContext=applicationContext;
    }


    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getHandler(String name, Class<T> cls) {
        T t = null;
        if (!StringUtils.hasText(name)) {
            checkApplicationContext();

            try {
                t = applicationContext.getBean(name, cls);
            } catch (Exception var4) {
                log.error("####################" + name + "未定义");
            }
        }

        return t;
    }

    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return applicationContext.getBean(clazz);
    }

    public static void cleanApplicationContext() {
        applicationContext = null;
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContext");
        }
    }
}
